/**
 * @Project Name :  als-rpc
 * @Package Name :  com.alvis.utilities
 * @Description :  TODO
 * @author :  Alvis
 * @Creation Date:  2018-07-05 1:25 PM
 * @ModificationHistory Who    When    What
 * --------  ---------  --------------------------
 */
package com.alvis.utilities;

import com.alvis.config.RpcConfig;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author :  Alvis
 * @Description :  TODO
 * @Creation Date:  2018-07-05 1:25 PM
 */
public class NetWorkHelper {

    static String localHost;


    public static String getLocalHost() {
        try {
            if (null == localHost) {
                InetAddress inetAddress = NetWorkHelper.getLocalHostLANAddress();
                localHost = inetAddress.toString().replace("/", "") + ":" + RpcConfig.getPort();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return localHost;
    }

    private static InetAddress getLocalHostLANAddress() throws Exception {
        try {
            InetAddress candidateAddress = null;
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
                NetworkInterface networkInterface = (NetworkInterface) ifaces.nextElement();
                if (networkInterface.getDisplayName().toLowerCase().contains("virtual")) {
                    continue;
                }
                for (Enumeration inetAddresses = networkInterface.getInetAddresses(); inetAddresses.hasMoreElements(); ) {
                    InetAddress inetAddress = (InetAddress) inetAddresses.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        if (inetAddress.isSiteLocalAddress()) {
                            return inetAddress;
                        } else if (candidateAddress == null) {
                            candidateAddress = inetAddress;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            return jdkSuppliedAddress;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
